<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-row>
        <el-form :model="listQuery">
          <el-col :span="6">
            <el-form-item label="订单编号/用户昵称">
              <el-input v-model="listQuery.keyWord" clearable class="filter-item" style="width: 200px;"
                placeholder="请输入订单编号/用户昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单创建时间">
              <el-date-picker v-model="queryParam.timeArray" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss"
                class="filter-item" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                :picker-options="pickerOptions" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="订单状态">
              <el-select clearable v-model="listQuery.orderStatus" multiple style="width: 200px" class="filter-item"
                placeholder="请选择订单状态">
                <el-option v-for="item in orderStatusList" :key="item.dictDataId" :label="item.dictDataName"
                  :value="item.dictDataCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button class="filter-item btn" icon="el-icon-refresh-right" @click="handleReset">重置</el-button>
            <el-button class="filter-item btn" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
          </el-col>
        </el-form>
      </el-row>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column type="expand">
        <template slot-scope="props">
          <div v-for="item in props.row.productList" :key="item.pid" class="order-goods">
            <div class="picture">
              <img :src="item.pic" width="40">
            </div>
            <div class="name">
              商品名称：{{ item.productName }}
            </div>
            <div class="price">
              单价：{{ item.productPrice }} 元
            </div>
            <div class="num">
              数量：{{ item.productNumber }} 件
            </div>
            <div class="price">
              小计：{{ item.productPrice * item.productNumber }} 元
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column align="center" min-width="120" label="订单编号" prop="orderNumber" />

      <el-table-column align="center" label="下单用户" prop="userFullName" />

      <el-table-column align="center" label="下单时间" prop="createTime" min-width="100">
        <template slot-scope="scope">
          {{ (scope.row.createTime || '-') }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="下单店铺" prop="shopName" min-width="100">
        <template slot-scope="scope">
          {{ (scope.row.shopName || '-') }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="订单状态" prop="orderStatusStr">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.orderStatusStr }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="订单金额" prop="totalPay">
        <template slot-scope="scope">
          {{ scope.row.totalPay }} 元
        </template>
      </el-table-column>

      <el-table-column align="center" label="实付金额" prop="actualPay">
        <template slot-scope="scope">
          {{ scope.row.actualPay }} 元
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="300" class-name="oper">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleDetail(scope.row)">详情</el-button>
          <!--          <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>-->
          <el-button v-if="scope.row.orderStatus != '3'" type="danger" size="small"
            @click="handleCancel(scope.row)">取消</el-button>
          <!-- <el-button type="primary" size="small" @click="handleVerify(scope.row)">核销</el-button> -->
          <el-button v-if="scope.row.orderStatus != '3'" type="danger" size="small"
            @click="handleRefund(scope.row)">退款</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize"
      @pagination="getList" />

    <!-- 订单详情对话框 -->
    <el-dialog :visible.sync="orderDialogVisible" title="订单详情" width="800">
      <section ref="print">
        <el-form :data="orderDetail" label-position="left">
          <el-form-item label="订单编号">
            <span>{{ orderDetail.orderNumber }}</span>
          </el-form-item>
          <el-form-item label="订单状态">
            <el-tag>{{ orderDetail.orderStatusStr }}</el-tag>
          </el-form-item>
          <el-form-item label="订单用户">
            <span>{{ orderDetail.userName }}</span>
          </el-form-item>
          <el-form-item label="用户留言">
            <span>{{ orderDetail.buyerMessage }}</span>
          </el-form-item>
          <el-form-item label="订单创建时间">
            <span>{{ orderDetail.createTime }}</span>
          </el-form-item>
          <el-form-item label="商品信息">
            <el-table :data="orderDetail.productList" border fit highlight-current-row>
              <el-table-column align="center" label="商品名称" prop="productName" />
              <el-table-column align="center" label="货品价格" prop="productPrice" />
              <el-table-column align="center" label="货品数量" prop="productNumber" />
              <el-table-column align="center" label="货品图片" prop="pic">
                <template slot-scope="scope">
                  <img :src="scope.row.pic" width="40">
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="费用信息">
            <span>
              (实际费用) {{ orderDetail.actualPay }}元
            </span>
          </el-form-item>
          <el-form-item label="支付信息">
            <span>（支付渠道）{{ orderDetail.paymentTypeStr }}</span>
            <!--            <span>（支付时间）{{ orderDetail.createTime }}</span>-->
          </el-form-item>
          <el-form-item v-if="orderDetail.refundPay" label="退款信息">
            <span>（退款金额）{{ orderDetail.refundPay }}元</span>
          </el-form-item>
        </el-form>
      </section>
      <span slot="footer" class="dialog-footer">
        <el-button @click="orderDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="printOrder">确认</el-button>
      </span>
    </el-dialog>

    <!-- 收款对话框 -->
    <!-- <el-dialog :visible.sync="payDialogVisible" title="订单收款" width="40%" center>
      <el-form ref="payForm" :model="payForm" status-icon label-position="left" label-width="100px">
        <div style="margin-bottom: 10px;">
          确认当前订单（订单编号 {{ payForm.orderNumber }} ) 已经完成线下收款 ？
        </div>
        <el-form-item label="订单金额" prop="oldMoney">
          <el-input-number v-model="payForm.oldMoney" :controls="false" disabled />
        </el-form-item>
        <el-form-item label="付款金额" prop="newMoney">
          <el-input-number v-model="payForm.newMoney" :controls="false" />
        </el-form-item>
      </el-form>
      <el-table :data="payForm.productList">
        <el-table-column property="productName" label="商品" />
        <el-table-column label="单价">
          <template slot-scope="scope">
            {{ scope.row.productPrice }} ￥
          </template>
        </el-table-column>
        <el-table-column property="onumber" width="100" label="下单数量" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="payDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPay">确定</el-button>
      </div>
    </el-dialog> -->

    <!-- 退款对话框 -->
    <el-dialog :visible.sync="refundDialogVisible" title="退款">
      <el-form ref="refundForm" :model="refundForm" status-icon label-position="left" label-width="100px"
        style="width: 400px; margin-left:50px;">
        <el-form-item label="退款金额" prop="refundMoney">
          <el-input v-model="refundForm.refundMoney" :disabled="false" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRefund">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>


<script>
import { detailOrder, listOrder, listChannel, shipOrder, setOrderStatus } from '@/api/order'
import { listDictData } from '@/api/dict'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import checkPermission from '@/utils/permission' // 权限判断函数
import Cookies from 'js-cookie'

export default {
  name: 'Order',
  components: { Pagination },
  filters: {
    orderStatusFilter(status) {
      // return statusMap[status]
    }
  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        shopId: Cookies.get("shopId"),
        currentPage: 1,
        pageSize: 20,
        keyWord: "",
        orderStatus: []
      },
      queryParam: {
        timeArray: []
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      orderStatusList: [],
      ostcQuery: {
        typeCode: 'DDZT'
      },
      orderDialogVisible: false,
      orderDetail: {
        productList: []
      },
      shipForm: {
        orderId: undefined,
        shipChannel: undefined,
        shipSn: undefined
      },
      shipDialogVisible: false,
      payForm: {
        orderId: undefined,
        orderNumber: '',
        oldMoney: 0,
        newMoney: 0,
        productList: []
      },
      payDialogVisible: false,
      refundForm: {
        orderId: undefined,
        refundMoney: undefined
      },
      refundDialogVisible: false,
      downloadLoading: false,
      channels: []
    }
  },
  created() {
    this.getList()
    this.getOrderStatusList()
    // this.getChannel()
  },
  methods: {
    checkPermission,
    getList() {
      this.listLoading = true
      if (this.queryParam.timeArray && this.queryParam.timeArray.length === 2) {
        this.listQuery.startTime = this.queryParam.timeArray[0]
        this.listQuery.endTime = this.queryParam.timeArray[1]
      } else {
        this.listQuery.startTime = null
        this.listQuery.endTime = null
      }
      if (this.listQuery.orderId) {
        detailOrder(this.listQuery.orderId).then(response => {
          this.list = []
          if (response.data.order) {
            this.list.push(response.data.order)
            this.total = 1
            this.listLoading = false
          }
        }).catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
      } else {
        listOrder(this.listQuery).then(response => {
          this.list = response.data.records
          this.total = response.data.total
          this.listLoading = false
        }).catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
      }
    },
    // 获取字典数据（订单状态）
    getOrderStatusList() {
      listDictData(this.ostcQuery).then(res => {
        this.orderStatusList = res.data
      })
    },
    getChannel() {
      listChannel().then(response => {
        this.channels = response.data
      })
    },
    handleFilter() {
      this.listQuery.currentPage = 1
      this.getList()
    },
    handleDetail(row) {
      detailOrder(row.orderId).then(response => {
        this.orderDetail = response.data
      })
      this.orderDialogVisible = true
    },
    // 点击付款按钮处理
    handlePay(row) {
      this.payForm.orderId = row.orderId
      this.payForm.orderNumber = row.orderNumber
      this.payForm.oldMoney = row.actualPay
      this.payForm.newMoney = row.actualPay
      this.payForm.productList = row.productList
      this.payForm.productList.forEach(element => {
        element.onumber = element.productNumber
      })
      this.payDialogVisible = true
    },
    // 取消订单
    handleCancel(row) {
      setOrderStatus({ orderId: row.orderId, orderStatus: '4' }).then(res => {
        if (res.code === 200) {
          this.$notify.success({
            title: '成功',
            message: '订单取消成功'
          })
          this.getList()
        } else {
          this.$notify.error({
            title: '失败',
            message: res.msg
          })
        }
      }).catch(res => {
        this.$notify.error({
          title: '失败',
          message: res.msg
        })
      })
    },
    // 确认收款后判断
    confirmPay() {
      if (this.payForm.oldMoney !== this.payForm.newMoney) {
        const diff = this.payForm.newMoney - this.payForm.oldMoney
        this.$confirm('差额 ' + diff + '元， 是否确认提交')
          .then(_ => {
            this.confirmPay2()
          })
          .catch(_ => { })
      } else {
        this.confirmPay2()
      }
    },
    // 确认收款
    confirmPay2() {
      setOrderStatus({ orderId: this.payForm.orderId, orderStatus: '1' }).then(res => {
        if (res.data.code === 200) {
          this.$notify.success({
            title: '成功',
            message: '订单收款操作成功'
          })
          this.getList()
        } else {
          this.$notify.error({
            title: '失败',
            message: res.data.msg
          })
        }
      }).catch(res => {
        this.$notify.error({
          title: '失败',
          message: res.data.msg
        })
      }).finally(() => {
        this.payDialogVisible = false
      })
    },
    // 处理核销
    handleVerify(row) {
      setOrderStatus({ orderId: row.orderId, orderStatus: '2' }).then(res => {
        if (res.code === 200) {
          this.$notify.success({
            title: '成功',
            message: '订单核销操作成功'
          })
          this.getList()
        } else {
          this.$notify.error({
            title: '失败',
            message: res.msg
          })
        }
      }).catch(res => {
        console.log(res)
        this.$notify.error({
          title: '失败',
          message: res.msg
        })
      })
    },
    handleShip(row) {
      this.shipForm.orderId = row.id
      this.shipForm.shipChannel = row.shipChannel
      this.shipForm.shipSn = row.shipSn

      this.shipDialogVisible = true
      this.$nextTick(() => {
        this.$refs['shipForm'].clearValidate()
      })
    },
    confirmShip() {
      this.$refs['shipForm'].validate((valid) => {
        if (valid) {
          shipOrder(this.shipForm).then(response => {
            this.shipDialogVisible = false
            this.$notify.success({
              title: '成功',
              message: '确认发货成功'
            })
            this.getList()
          }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
        }
      })
    },
    //重置
    handleReset() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        keyWord: '',
        orderStatus: []
      }
      this.getList();
    },
    // handleDelete(row) {
    //   deleteOrder({ orderId: row.id }).then(response => {
    //     this.$notify.success({
    //       title: '成功',
    //       message: '订单删除成功'
    //     })
    //     this.getList()
    //   }).catch(response => {
    //     this.$notify.error({
    //       title: '失败',
    //       message: response.data.errmsg
    //     })
    //   })
    // },
    // 退款按钮处理
    handleRefund(row) {
      this.refundForm.orderId = row.orderId
      this.refundForm.refundMoney = row.actualPay

      this.refundDialogVisible = true
      this.$nextTick(() => {
        this.$refs['refundForm'].clearValidate()
      })
    },
    // 退款确认处理
    confirmRefund() {
      this.$refs['refundForm'].validate((valid) => {
        if (valid) {
          setOrderStatus({ orderId: this.refundForm.orderId, orderStatus: '3', refundPay: this.refundForm.refundMoney }).then(res => {
            if (res.data.code === 200) {
              this.$notify.success({
                title: '成功',
                message: '确认退款成功'
              })
              this.getList()
            } else {
              this.$notify.error({
                title: '失败',
                message: res.data.msg
              })
            }
          }).catch(res => {
            this.$notify.error({
              title: '失败',
              message: res.data.msg
            })
          }).finally(() => {
            this.refundDialogVisible = false
          })
        }
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['订单ID', '订单编号', '用户ID', '订单状态', '是否删除', '收货人', '收货联系电话', '收货地址']
        const filterVal = ['id', 'orderSn', 'userId', 'orderStatus', 'isDelete', 'consignee', 'mobile', 'address']
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '订单信息')
        this.downloadLoading = false
      })
    },
    printOrder() {
      // this.$print(this.$refs.print)
      this.orderDialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-item {
  text-align: left;
  margin-left: 20px;

  &.btn {
    float: right;
    margin-right: 5px;
  }
}

.el-table--medium th,
.el-table--medium td {
  padding: 3px 0;
}

.el-input-number--medium {
  width: 100%;
}

.oper .el-button--mini {
  padding: 7px 4px;
  width: 40px;
  font-size: 10px;
  margin-left: 1px;
}

::v-deep .el-table__expanded-cell {
  padding: 6px 80px;
}

.order-goods {
  display: flex;
  justify-content: space-around;
  justify-items: center;
  align-items: center;
  padding: 6px 0;
}

.name {
  width: 400px;
}

.spec {
  width: 180px;
}

.price {
  width: 120px;
}

.num {
  width: 120px;
}
</style>